package com.frame.compiler.base;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;

import androidx.multidex.MultiDex;

import com.bumptech.glide.Glide;
import com.coder.zzq.smartshow.core.SmartShow;
import com.frame.compiler.net.Custom_PersistentCookieStore;
import com.frame.compiler.utils.LogUtils;
import com.frame.compiler.utils.RxTool;
import com.frame.compiler.utils.ThreadUtils;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;

import org.litepal.LitePal;

import java.net.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * project:PJHAndroidFrame
 * package:com.frame.pjhandroidframe.base
 * Created by 彭俊鸿 on 2018/6/22.
 * e-mail : 1031028399@qq.com
 * Application基类
 */

public class BaseApplication extends Application {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        RxTool.init(this);
        String curProcessName =getProcessName(this, android.os.Process.myPid());
        if (curProcessName != null && curProcessName.equalsIgnoreCase(this.getPackageName())) {
            mainThreadInit();
        }
    }

    //在主进程中初始化
    public void mainThreadInit(){
        ThreadUtils.getSinglePool().execute(new Runnable() {
            @Override
            public void run() {
                initX5WebView();
                asyncMethod();
            }
        });
        SmartShow.init(this);
        initOkGo();
        initLitePal();
    }

    //异步方法进行初始化
    public void asyncMethod() {

    }

    //初始化网络请求库
    private void initOkGo() {
        CookieJarImpl cookieJar = new CookieJarImpl(new Custom_PersistentCookieStore(getApplicationContext()));

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .proxy(Proxy.NO_PROXY)
                .connectTimeout(60000L, TimeUnit.MILLISECONDS)
                .readTimeout(60000L, TimeUnit.MILLISECONDS)
                //其他配置
                .cookieJar(cookieJar)
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }

    //初始化webview
    private void initX5WebView() {
        // 在调用TBS初始化、创建WebView之前进行如下配置
        HashMap map = new HashMap();
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
        QbSdk.initTbsSettings(map);
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                LogUtils.e("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    //初始化数据库
    private void initLitePal() {
        LitePal.initialize(this);
    }

    // 获取进程名
    public String getProcessName(Context cxt, int pid) {
        android.app.ActivityManager am = (android.app.ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (android.app.ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    /**
     * 低内存的时候执行
     */
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Glide.get(this).clearMemory();
    }

    /**
     * HOME键退出应用程序
     * 程序在内存清理的时候执行
     */
    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level == TRIM_MEMORY_UI_HIDDEN) {
            Glide.get(this).clearMemory();
        }
        Glide.get(this).trimMemory(level);
    }
}
